package com.example.lushudao_admin.realm;


import com.example.lushudao_admin.entity.Admin;
import com.example.lushudao_admin.service.impl.AdminServiceImpl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminServiceImpl adminServiceImpl;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Subject subject= SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        //设置角色
        Set<String> roles=new HashSet<>();
        roles.add(admin.getRole());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        //设置权限
        info.addStringPermission(admin.getPerms());
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        Admin admin = adminServiceImpl.loginCheckUserAcc(token.getUsername());
        if (admin!=null){
            return new SimpleAuthenticationInfo(admin,admin.getAdmin_pwd(),getName());
        }
        return null;
    }
}
